from paste import httpexceptions
from brightcontent.util import get_base_url

class TrailingSlashMiddleware(object):
    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        """
        Middleware to check if the request is for a file (contains a
        '.' and some extension). If it is for a directory then it
        appends the trailing slash and redirects with a 303 Moved
        Permanently code.
        """
        path_info = environ['PATH_INFO']
        if not path_info.endswith('/'):
            if not '.' in path_info.split('/').pop():
                new_loc = get_base_url(environ)
                if path_info != '/' and path_info != '':
                    new_loc += path_info.lstrip('/') + '/'
                raise httpexceptions.HTTPMovedPermanently(headers=[('location', '%s' % new_loc)])
        return self.app(environ, start_response)

def make_filter(app, *global_conf, **app_conf):
    """
    Creates a TrailingSlashMiddleware application filter that can be
    used in a paste config file as a filter.
    """
    def filter(app):
        app = TrailingSlashMiddleware(app)
        return httpexceptions.make_middleware(app, global_conf) 
    return filter
